package com.example.lin.day10_17_bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.le.BluetoothLeScanner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.skydoves.colorpickerview.ColorEnvelope;
import com.skydoves.colorpickerview.ColorPickerView;
import com.skydoves.colorpickerview.listeners.ColorEnvelopeListener;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
import java.util.UUID;

public class MainClientActivity extends AppCompatActivity implements BluetoothRVAdapter.OnRVItemClickListener {

    private static final String TAG = MainClientActivity.class.getSimpleName();
    //蓝牙适配器
    private BluetoothAdapter defaultAdapter;
    private RecyclerView recyclerView;

    private RecyclerView localRV;

    private BluetoothRVAdapter bluetoothRVAdapter;
    private BluetoothRVAdapter localRVAdapter;
    private BluetoothSocket bluetoothSocket;
    private PrintWriter pw;
    private DataOutputStream dataOutputStream;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }


        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        bluetoothRVAdapter = new BluetoothRVAdapter(this);
        recyclerView.setAdapter(bluetoothRVAdapter);
        bluetoothRVAdapter.setOnRVItemClickListener(this);

        localRV = findViewById(R.id.localRV);
        localRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        localRV.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        localRVAdapter = new BluetoothRVAdapter(this);
        localRV.setAdapter(localRVAdapter);
        localRVAdapter.setOnRVItemClickListener(this);

        //获取蓝牙适配器
        defaultAdapter = BluetoothAdapter.getDefaultAdapter();


    }


    public void openBluetooth(View view) {
        if (defaultAdapter != null) {
            Toast.makeText(this, "手机支持蓝牙", Toast.LENGTH_SHORT).show();
            //判断蓝牙是否打开
//            if (!defaultAdapter.isEnabled()) {
//                //请求打开蓝牙
//                startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
//            }
            //判断蓝牙是否打开
            if (!defaultAdapter.isEnabled()) {
                //强制打开蓝牙,在高版本(6.0以上) 还是会弹出提示框请求用户同意
                defaultAdapter.enable();
            }
        } else {
            Toast.makeText(this, "手机不支持蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    public void discoverableBluetooth(View view) {
        //判断蓝牙是否打开
        if (defaultAdapter.isEnabled()) {
            //请求蓝牙可以被发现(7.0之后,打开蓝牙默认可被发现)
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //配置蓝牙可被发现的时长(/s)
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);
            startActivity(intent);
        }
    }


    /**
     * 获取已配对过的蓝牙设备
     */
    public void getLocalBluetooth(View view) {

        if (defaultAdapter != null) {
            Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();
            if (bondedDevices != null && bondedDevices.size() > 0) {

                for (BluetoothDevice device : bondedDevices) {
                    Log.d(TAG, "getLocalBluetooth: " + device.getAddress() + "," + device.getName());
                    if (!TextUtils.isEmpty(device.getName()))
                        localRVAdapter.addDevice(device);
                }

            }


        }
    }

    //搜索附近蓝牙设备
    public void searchBluetooth(View view) {

        if (defaultAdapter != null) {
            if (bluetoothReceiver == null) {
                bluetoothReceiver = new BluetoothReceiver();
                //注册广播接收者,接收蓝牙搜索到的设备信息
                registerReceiver(bluetoothReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
            }
            defaultAdapter.startDiscovery();//开始扫描附近的蓝牙设备,搜索结果以广播的形式发送.
        }
    }

    private BluetoothReceiver bluetoothReceiver;


    private void showDialogSendColor() {
        final View layout = LayoutInflater.from(this).inflate(R.layout.view_dialog, null);
        ColorPickerView colorPickerView = layout.findViewById(R.id.colorPickerView);
        colorPickerView.setColorListener(new ColorEnvelopeListener() {

            private long lastTime = 0;

            @Override
            public void onColorSelected(ColorEnvelope envelope, boolean fromUser) {
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastTime > 50) {
                    int color = envelope.getColor();
                    sendColor(color);
                } else {
                    lastTime = currentTime;
                }
            }
        });
        new AlertDialog.Builder(this)
                .setTitle("发送颜色")
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (dataOutputStream != null) {
                            try {
                                dataOutputStream.flush();
                                dataOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (bluetoothSocket != null) {
                            try {
                                bluetoothSocket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                })
                .setView(layout).show();
    }

    @Override
    public void onItemClick(BluetoothDevice device, View view, int position) {

        if (defaultAdapter == null)
            return;
//        bluetoothRVAdapter.clears();


        Log.i(TAG, "onItemClick: " + device.getAddress() + "," + device.getName());
        //蓝牙设备是否还在搜索中...
        if (defaultAdapter.isDiscovering()) {
            defaultAdapter.cancelDiscovery();//结束搜索
        }
        String address = device.getAddress();
        BluetoothDevice remoteDevice = defaultAdapter.getRemoteDevice(address);
        //得到 与远程设备的 配对状态
        int bondState = remoteDevice.getBondState();
        Log.d(TAG, "onItemClick: " + bondState);
        //与远程设备没有配对,
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        try {
            //开始配对连接(uuid必须与 远程蓝牙设备的一致)
            bluetoothSocket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
            //开始连接
            bluetoothSocket.connect();
            Log.d(TAG, "onItemClick: 连接成功!");
            //与远程服务端 建立IO流   输出流
            dataOutputStream = new DataOutputStream(bluetoothSocket.getOutputStream());
            showDialogSendColor();
//            pw = new PrintWriter(new OutputStreamWriter(bluetoothSocket.getOutputStream(), "UTF-8"));
            Log.d(TAG, "onItemClick: 成功建立IO流");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "onItemClick: \"连接失败!\"", e);
        }
//        if (bondState == BluetoothDevice.BOND_NONE) {
//        } else if (bondState == BluetoothDevice.BOND_BONDED) {
//            //与远程设备已经配对
//
//        } else {
//            //与远程设备正在配对中
//
//        }
    }

    /**
     * 蓝牙广播接收者,接收搜索到的设备信息
     */
    class BluetoothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int type = 0;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    type = device.getType();
                }
                Log.d(TAG, "onReceive: " + device.getAddress() + "," + type + "," + device.getName());
                if (!TextUtils.isEmpty(device.getName()))
                    bluetoothRVAdapter.addDevice(device);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothReceiver != null) {
            unregisterReceiver(bluetoothReceiver);
        }
    }


    private void sendColor(int color) {
//        写输出给服务端
        try {
            Log.d(TAG, "sendColor: 输出数据" + color);
            dataOutputStream.writeInt(color);
            dataOutputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "sendColor: 输出异常");
        }
    }

}
